import SparkMD5 from './spark-md5'

onmessage = async (e) => {
    const {file, start, end, CHUNK_SIZE} = e.data
    const result = []
    for (let i = start; i < end; i++) {
        const prom = createChunk(file, i, CHUNK_SIZE)
        result.push(prom)
    }
    const chunks = await Promise.all(result)
    postMessage(chunks)
}


/**
 * 创建分片
 * @param file 需要分片的文件
 * @param index  当前分片索引
 * @param chunkSize 分片大小
 * @returns {Promise<void>} 分片文件
 */
async function createChunk(file, index, chunkSize) {
    return new Promise((resolve) => {
        const start = index * chunkSize
        const end = start + chunkSize
        const spark = new SparkMD5.ArrayBuffer()
        const fileReader = new FileReader()
        const blob = file.slice(start, end)
        fileReader.onload = (e) => {
            spark.append(e.target.result)
            resolve({
                start,
                end,
                index,
                hash: spark.end(), // 唯一标识符
                blob
            })
        }
        fileReader.readAsArrayBuffer(blob)
    })
}